package com.lovcreate.listener;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by Administrator on 2016/7/23.
 */
@WebServlet(name = "JdbcListenerTester", urlPatterns = {"/JdbcListenerTester"})
public class JdbcListenerTester extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out = response.getWriter();
        String title = "数据库结果";
        String docType =
                "<!doctype html public \"-//w3c//dtd html 4.0 " +
                        "transitional//en\">\n";
        out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n");

        Connection conn = (Connection) getServletContext().getAttribute("conn");    // 通过上下文属性获得数据库连接
        String sql = "select * from employees";
        PreparedStatement pstmt;
        try {
            pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery(sql);
            int col = rs.getMetaData().getColumnCount();
            out.println("================================");
            while (rs.next()) {
                for (int i = 1; i <= col; i++) {
                    out.println(rs.getString(i) + "\t");
                }
                out.println();
            }
            out.println("================================");
        } catch (SQLException e) {
            // 处理 JDBC 错误
            e.printStackTrace();
        }
    }
}
